package com.fengzhi.crawler.jsoup.thread;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

import com.fengzhi.crawler.jsoup.Fetcher.ImgFetcher;
import com.fengzhi.crawler.jsoup.Fetcher.impl.ImgFetcherImpl;
import com.fengzhi.crawler.jsoup.queue.ImgQueue;
import com.fengzhi.crawler.jsoup.queue.LinkQueue;

public class CrawlerImgThread implements Runnable {

	private CountDownLatch latch;
	private String dir;

	public CrawlerImgThread(CountDownLatch latch, String dir) {
		this.latch = latch;
		this.dir = dir;
	}

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName() + " : " + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS").format(new Date()));

		boolean isWork = true;

		while (isWork) {
			if (LinkQueue.unVisitedUrlIsEmpty() && ImgQueue.unDownLoadImgUrlIsEmpty()) {
				isWork = false;
			} else {

				if (ImgQueue.unDownLoadImgUrlIsEmpty()) {
					continue;
				} else {
					String imgUrl = ImgQueue.unDownLoadImgUrlDeQueue();
					
					System.out.println("---------+++++++++++---------");
					
					ImgFetcher fetch = new ImgFetcherImpl();
					fetch.fetch(imgUrl, dir);
				}
			}
		}

		System.out.println(Thread.currentThread().getName() + " : " + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS").format(new Date()));
		latch.countDown();
	}

}
